package com.prawn.ift_collequipment.service;

import java.util.*;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Expression;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.persistence.criteria.Selection;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import util.IdWorker;

import com.prawn.ift_collequipment.dao.EquipmentTypeDao;
import com.prawn.ift_collequipment.pojo.EquipmentType;

/**
 * 服务层
 * 
 * @author Administrator
 *
 */
@Service
public class EquipmentTypeService {

	@Autowired
	private EquipmentTypeDao equipmentTypeDao;
	
	@Autowired
	private IdWorker idWorker;

	/**
	 * 查询全部列表
	 * @return
	 */
	public List<EquipmentType> findAll() {
		return equipmentTypeDao.findAll();
	}

	
	/**
	 * 条件查询+分页
	 * @param whereMap
	 * @param page
	 * @param size
	 * @return
	 */
	public Page<EquipmentType> findSearch(Map whereMap, int page, int size) {
		Specification<EquipmentType> specification = createSpecification(whereMap);
		PageRequest pageRequest =  PageRequest.of(page-1, size);
		return equipmentTypeDao.findAll(specification, pageRequest);
	}

	
	/**
	 * 条件查询
	 * @param whereMap
	 * @return
	 */
	public List<EquipmentType> findSearch(Map whereMap) {
		Specification<EquipmentType> specification = createSpecification(whereMap);
		return equipmentTypeDao.findAll(specification);
	}

	/**
	 * 根据ID查询实体
	 * @param id
	 * @return
	 */
	@Cacheable(value = "equipmentType",key = "#id")
	public EquipmentType findById(String id) {
		return equipmentTypeDao.findById(id).get();
	}

	/**
	 * 增加
	 * @param equipmentType
	 */
	public void add(EquipmentType equipmentType) {
		equipmentType.setId( idWorker.nextId()+"" );
		equipmentTypeDao.save(equipmentType);
	}

	/**
	 * 修改
	 * @param equipmentType
	 */
	@CacheEvict(value = "equipmentType",key = "#equipmentType.id")
	public void update(EquipmentType equipmentType) {
		equipmentTypeDao.save(equipmentType);
	}

	/**
	 * 删除
	 * @param id
	 */
	@CacheEvict(value = "equipmentType",key = "#id")
	public void deleteById(String id) {
		equipmentTypeDao.deleteById(id);
	}

	/**
	 * 动态条件构建
	 * @param searchMap
	 * @return
	 */
	private Specification<EquipmentType> createSpecification(Map searchMap) {

		return new Specification<EquipmentType>() {

			@Override
			public Predicate toPredicate(Root<EquipmentType> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
				List<Predicate> predicateList = new ArrayList<Predicate>();
                // 编号
                if (searchMap.get("id")!=null && !"".equals(searchMap.get("id"))) {
                	predicateList.add(cb.like(root.get("id").as(String.class), "%"+(String)searchMap.get("id")+"%"));
                }
                // 类型名称
                if (searchMap.get("name")!=null && !"".equals(searchMap.get("name"))) {
                	predicateList.add(cb.like(root.get("name").as(String.class), "%"+(String)searchMap.get("name")+"%"));
                }
                // 父类编号
                if (searchMap.get("parentId")!=null && !"".equals(searchMap.get("parentId"))) {
                	predicateList.add(cb.like(root.get("parentId").as(String.class), "%"+(String)searchMap.get("parentId")+"%"));
                }
                //  多层父id串
                if (searchMap.get("parentIds")!=null && !"".equals(searchMap.get("parentIds"))) {
                	predicateList.add(cb.like(root.get("parentIds").as(String.class), "%"+(String)searchMap.get("parentIds")+"%"));
                }
                // 备注信息
                if (searchMap.get("remarks")!=null && !"".equals(searchMap.get("remarks"))) {
                	predicateList.add(cb.like(root.get("remarks").as(String.class), "%"+(String)searchMap.get("remarks")+"%"));
                }
                // 创建者
                if (searchMap.get("createBy")!=null && !"".equals(searchMap.get("createBy"))) {
                	predicateList.add(cb.like(root.get("createBy").as(String.class), "%"+(String)searchMap.get("createBy")+"%"));
                }
                // 更新者
                if (searchMap.get("updateBy")!=null && !"".equals(searchMap.get("updateBy"))) {
                	predicateList.add(cb.like(root.get("updateBy").as(String.class), "%"+(String)searchMap.get("updateBy")+"%"));
                }
                // 删除标记（虚拟删除，并不删除数据库表数据，0：正常，1：删除）
                if (searchMap.get("delFlag")!=null && !"".equals(searchMap.get("delFlag"))) {
                	predicateList.add(cb.like(root.get("delFlag").as(String.class), "%"+(String)searchMap.get("delFlag")+"%"));
                }
				
				return cb.and( predicateList.toArray(new Predicate[predicateList.size()]));

			}
		};

	}
	/**
	 * 查询场景分类信息列表，并生成树形数据
	 * @return List<EquipmentType>
	 */

	public List<EquipmentType> getEquipmentTypeTree() {
		//获取所有分类
		List<EquipmentType> equipmentTypeList = this.findAll();
		//获取顶级分类
		List<EquipmentType> rootEquipmentTypeList = this.getEquipmentTypeByPid("0");

		for (EquipmentType equipmentType : rootEquipmentTypeList) {
			//每个分类项目都设置其子分类
			equipmentType.setChildren(getChild(equipmentType.getId(),equipmentTypeList));
		}
		return rootEquipmentTypeList;
	}

	/**
	 * 根据父id获取
	 * @param parentId
	 * @return
	 */
	private List<EquipmentType> getEquipmentTypeByPid(String parentId) {

		List<EquipmentType> result=equipmentTypeDao.findAll(new Specification<EquipmentType>() {
			@Override
			public Predicate toPredicate(Root<EquipmentType> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
				if (parentId!=null && !"".equals(parentId)){
					return criteriaBuilder.equal(root.get("parentId").as(String.class),parentId);
				}
				return null;
			}
		});
		return result;
	}

	/**
	 * 递归查询子分类
	 * @param id
	 * @param equipmentTypeList
	 * @return ResponseMessage
	 */
	private List<EquipmentType> getChild(String id, List<EquipmentType> equipmentTypeList) {
		//返回的子菜单
		List<EquipmentType> childList = new ArrayList<>();

		// 遍历所有节点，将父菜单id与传过来的id比较
		for (EquipmentType equipmentType : equipmentTypeList) {
			if (equipmentType.getParentId() != null) {
				//如果列表中的父id等于当前的分类的id，那就加入到该分类子列表中
				if (equipmentType.getParentId().equals(id)) {
					childList.add(equipmentType);
				}
			}
		}

		// 把子菜单的子菜单childList再循环一遍
		for (EquipmentType equipmentType : childList) {
			equipmentType.setChildren(getChild(equipmentType.getId(),equipmentTypeList));
		}

		//退出递归的条件
		if (childList.size() == 0) {
			return null;
		}

		return childList;
	}
}
